package lego

import (
	"github.com/mjiulee/lego/toolbox"
	"github.com/valyala/fasthttp"
	"time"
)

/*
 * 请求日志处理中间件
 ————————————————————————
*/
// Statistics struct
type Statistics struct {
	RequestURL        string
	RequestController string
	RequestNum        int64
	MinTime           time.Duration
	MaxTime           time.Duration
	TotalTime         time.Duration
}

func middlewareStatistics(next fasthttp.RequestHandler) fasthttp.RequestHandler {
	return fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) {
	//for optimise performance
		ctxExt := RequestCtxExtent{ctx}
		tsgroup := SetTsGroupInContext(&ctxExt)
		//ctx.SetUserValue(USER_VALUE_TS_GROUP, tsgroup)


		startTime := time.Now()
		next(ctx)

		Method := ctx.Method()
		//Path := ctx.RequestURI() 这种是完整路径，带?号后面的参数
		Path := ctx.Path()

		timeDur := time.Since(startTime)

		if timeDur >= 3*time.Second {
			toolbox.AppendToTimestampResult(tsgroup)
		}
		toolbox.StatisticsMap.SendStatisticsMsg(string(Method), string(Path), string(Path), timeDur)
	})
}

const USER_VALUE_TS_GROUP = "timestamp_group"
func GetTsGroupInContext(ctx *RequestCtxExtent) *[]*toolbox.Timestamp {
	tsGroup, ok := ctx.UserValue(USER_VALUE_TS_GROUP).(*[]*toolbox.Timestamp)
	if !ok {
		panic("GetTsGroupInContext: type assertion error!")
	}
	return tsGroup
}

func SetTsGroupInContext(ctx *RequestCtxExtent) *[]*toolbox.Timestamp {
	tsGroup := toolbox.NewTimestampGroup()
	ctx.SetUserValue(USER_VALUE_TS_GROUP, &tsGroup)

	return &tsGroup
}

